import React, { useState } from 'react'
import { Button } from '../ui/Button'
import { Badge } from '../ui/Badge'
import { ArxivCategory } from '../../types/auth'
import { ArrowLeft, ArrowRight, Plus, X } from 'lucide-react'

interface InterestSelectionStepProps {
  categories: ArxivCategory[]
  keywords: string[]
  authors: string[]
  onUpdate: (updates: any) => void
  onNext: () => void
  onPrevious: () => void
}

const categoryGroups = {
  'Computer Science': {
    'cs.AI': 'Artificial Intelligence',
    'cs.CL': 'Computation and Language',
    'cs.CV': 'Computer Vision',
    'cs.LG': 'Machine Learning',
    'cs.NE': 'Neural and Evolutionary Computing',
    'cs.RO': 'Robotics'
  },
  'Mathematics': {
    'math.AG': 'Algebraic Geometry',
    'math.AT': 'Algebraic Topology', 
    'math.CO': 'Combinatorics',
    'math.DG': 'Differential Geometry',
    'math.GM': 'General Mathematics',
    'math.GT': 'Geometric Topology'
  },
  'Physics': {
    'physics.app-ph': 'Applied Physics',
    'physics.atom-ph': 'Atomic Physics',
    'physics.comp-ph': 'Computational Physics',
    'physics.data-an': 'Data Analysis'
  },
  'Statistics': {
    'stat.AP': 'Applications',
    'stat.CO': 'Computation',
    'stat.ME': 'Methodology',
    'stat.ML': 'Machine Learning',
    'stat.TH': 'Statistics Theory'
  }
}

export function InterestSelectionStep({
  categories,
  keywords,
  authors,
  onUpdate,
  onNext,
  onPrevious
}: InterestSelectionStepProps) {
  const [newKeyword, setNewKeyword] = useState('')
  const [newAuthor, setNewAuthor] = useState('')

  const toggleCategory = (category: ArxivCategory) => {
    const updated = categories.includes(category)
      ? categories.filter(c => c !== category)
      : [...categories, category]
    onUpdate({ categories: updated })
  }

  const addKeyword = () => {
    if (newKeyword.trim() && !keywords.includes(newKeyword.trim())) {
      onUpdate({ keywords: [...keywords, newKeyword.trim()] })
      setNewKeyword('')
    }
  }

  const removeKeyword = (keyword: string) => {
    onUpdate({ keywords: keywords.filter(k => k !== keyword) })
  }

  const addAuthor = () => {
    if (newAuthor.trim() && !authors.includes(newAuthor.trim())) {
      onUpdate({ authors: [...authors, newAuthor.trim()] })
      setNewAuthor('')
    }
  }

  const removeAuthor = (author: string) => {
    onUpdate({ authors: authors.filter(a => a !== author) })
  }

  const canProceed = categories.length > 0

  return (
    <div className="bg-white rounded-xl shadow-sm p-8">
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">
          What are your research interests?
        </h2>
        <p className="text-gray-600">
          Select the areas you're most interested in. We'll use this to personalize your recommendations.
        </p>
      </div>

      <div className="space-y-8">
        {/* ArXiv Categories */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Research Areas
            <span className="text-sm font-normal text-gray-500 ml-2">
              (Select at least one)
            </span>
          </h3>
          
          <div className="space-y-6">
            {Object.entries(categoryGroups).map(([groupName, groupCategories]) => (
              <div key={groupName}>
                <h4 className="text-md font-medium text-gray-800 mb-3">{groupName}</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {Object.entries(groupCategories).map(([categoryId, categoryName]) => {
                    const isSelected = categories.includes(categoryId as ArxivCategory)
                    return (
                      <button
                        key={categoryId}
                        onClick={() => toggleCategory(categoryId as ArxivCategory)}
                        className={`p-3 text-left border rounded-lg transition-colors ${
                          isSelected
                            ? 'bg-blue-50 border-blue-300 text-blue-800'
                            : 'bg-gray-50 border-gray-200 text-gray-700 hover:bg-gray-100'
                        }`}
                      >
                        <div className="font-medium">{categoryName}</div>
                        <div className="text-sm text-gray-500">{categoryId}</div>
                      </button>
                    )
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Keywords */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Keywords <span className="text-sm font-normal text-gray-500">(Optional)</span>
          </h3>
          
          <div className="space-y-3">
            <div className="flex space-x-2">
              <input
                type="text"
                value={newKeyword}
                onChange={(e) => setNewKeyword(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addKeyword())}
                placeholder="e.g., neural networks, transformer, attention"
                className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
              />
              <Button onClick={addKeyword} disabled={!newKeyword.trim()}>
                <Plus className="h-4 w-4" />
              </Button>
            </div>
            
            {keywords.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {keywords.map(keyword => (
                  <Badge key={keyword} variant="secondary" className="pr-1">
                    {keyword}
                    <button
                      onClick={() => removeKeyword(keyword)}
                      className="ml-2 hover:bg-gray-200 rounded-full p-1"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Authors */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Favorite Authors <span className="text-sm font-normal text-gray-500">(Optional)</span>
          </h3>
          
          <div className="space-y-3">
            <div className="flex space-x-2">
              <input
                type="text"
                value={newAuthor}
                onChange={(e) => setNewAuthor(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addAuthor())}
                placeholder="e.g., Geoffrey Hinton, Yann LeCun"
                className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
              />
              <Button onClick={addAuthor} disabled={!newAuthor.trim()}>
                <Plus className="h-4 w-4" />
              </Button>
            </div>
            
            {authors.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {authors.map(author => (
                  <Badge key={author} variant="secondary" className="pr-1">
                    {author}
                    <button
                      onClick={() => removeAuthor(author)}
                      className="ml-2 hover:bg-gray-200 rounded-full p-1"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Navigation */}
      <div className="flex justify-between mt-8 pt-6 border-t border-gray-200">
        <Button variant="outline" onClick={onPrevious}>
          <ArrowLeft className="mr-2 h-4 w-4" /> Back
        </Button>
        
        <Button onClick={onNext} disabled={!canProceed}>
          Continue <ArrowRight className="ml-2 h-4 w-4" />
        </Button>
      </div>
      
      {!canProceed && (
        <p className="text-sm text-red-600 mt-2 text-center">
          Please select at least one research area to continue
        </p>
      )}
    </div>
  )
}